from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Article, Comment


# class CommentViewSet(APIView):
#     def post(self, request, id):
#         article = Article.objects.get(id=id)
#         user = request.user
#         content = request.data['content']
#         parent_id = request.data.get('parent')
#         article.comment_count = article.comment_count + 1
#         article.save()
#         if parent_id:
#             parent = Comment.objects.get(id = parent_id)
#             comment = Comment()
#             comment.parent = parent
#         else:
#             comment = Comment()
#             comment.article = article
#         comment.user = user
#         comment.content = content
#         comment.save()
#         return Response({
#                 "success": True,
#                 "message": "OK"
#             })


class CommentViewSet(APIView):

    def post(self, request, id):
        data = request.data
        data['user_id'] = request.user.id
        data.pop('article')
        data['article_id'] = id

        try:
            parent = data.pop('parent')
            data['parent_id'] = parent
        except Exception:
            pass
        com = Comment.objects.create(**data)
        com.article.comment_count += 1
        com.article.save()

        return Response({
            "message": "OK",
            "success": True
        })